#include "http_server.h"
#include "router_factory.h"
#include "logging.h"
#include "boost/regex.hpp"
#include "boost/tuple/tuple.hpp"
#include "app_admin.h"

std::string args = "";
void parse_arg(int argc, char* argv[])
{
	for (int i = 1; i < argc; i++)
	{
		args += argv[i];
		args += " ";
	}
}

boost::tuple<int, int> get_pos_len(std::string rgx_str)
{
	try
	{
		boost::regex rgx(rgx_str);
		boost::smatch result;
		if (boost::regex_search(args, result, rgx))
		{
			auto var = result[0].str();
			return boost::make_tuple(args.find(var), var.length());
		}
	}
	catch (std::exception& e)
	{
		LOGE(e.what());
	}
	return boost::make_tuple(-1, -1);
}

template<typename T>
T get_arg(const char* argk, T default_val)
{
	auto p_0 = get_pos_len(std::string("--") + argk + "\\s+\\w+\\s+");
	auto p_1 = get_pos_len(std::string("--") + argk + "\\s+");

	if (-1 == p_0.get<0>())
	{
		if (strcmp(argk, "file"))
		{
			LOGW("lose config arg for %s, use default %s", argk, boost::lexical_cast<std::string>(default_val))
		}
		return default_val;
	}

	auto var = args.substr(p_1.get<0>() + p_1.get<1>(), p_0.get<1>() - p_1.get<1>());
	var.erase(std::remove(var.begin(), var.end(), ' '), var.end());
	return boost::lexical_cast<T>(var);
}

int main(int argc, char *argv[])
{
	parse_arg(argc, argv);

	auto log_file = get_arg<std::string>("log", "./chttp.log");
	logger.set_log(log_file.c_str());

	int thread = 4;
	int port = 6001;

	auto config_file = get_arg<std::string>("file", "");
	if (!config_file.empty())
	{

	}
	else
	{
		port = get_arg<int>("port", 6001);
		thread = get_arg<int>("thread", 4);
	}

	LOGI("http listen on post %d", port);
	http_server server("0.0.0.0", port);
	server.register_router(new app_admin);
	server.multi_thread(thread).run();
	return 0;
}

